﻿using System;
using System.Collections.Generic;
using System.Data;
using Finance.ViewModels;

namespace Finance.Data.Entities
{
	public interface IProducts : IDataBaseObjectCollection<IProduct>
	{
		Guid GetOrCreateProduct(string productName);
	}
    
	internal class Products : DataBaseObjectCollection<IProduct>, IProducts
	{
		public Products(FinanceDataBase dataBase) : base(dataBase, "product") {}

		public Guid GetOrCreateProduct(string productName)
		{
			// try to find product
			var result = DataBase.Sql.ExecuteScalar("select productid from product where name = @p0", productName);
			if (result != null)
				return (Guid)result;

			//create new product
			var product = new Product(this) {Name = productName};
			Insert(product);
			return product.Id;
		}


		protected override void Update(IProduct item)
		{
			throw new NotImplementedException();
		}

		protected override void Insert(IProduct item)
		{
			item.Id = Guid.NewGuid();
			DataBase.Sql.ExecuteNonQuery("insert into product (productid, name) values (@p0, @p1)",
					item.Id,
					item.Name);
		}

		public override IProduct NewItem()
		{
			return new Product(this);
		}

		public IList<IProduct> GetAll()
		{
			var result = new List<IProduct>();
			using (var reader = DataBase.Sql.ExecuteReader("select * from product"))
			{
				while (reader.Read())
				{
					result.Add(ParseItem(reader));
				}
			}
			return result;
		}

		protected override IProduct ParseItem(IDataRecord reader)
		{
			return new Product(this)
				{
					Id = (Guid)reader["productid"],
					Name = (string)reader["name"]
				};
		}

		
	}
}
